package com.axialproject.health.exchange.demoacme;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class DemoServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(DemoServlet.class.getName());

    public void doPost (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String appUrl = this.getServletContext().getInitParameter("AppUrl");

        try {
            log.info ("Start connecting to connector");
            URL url = new URL(appUrl + "/demoacme/connector");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write("appName=" + URLEncoder.encode("demoacme", "UTF-8"));

            writer.write("&username=" + URLEncoder.encode(req.getParameter("username"), "UTF-8"));
            writer.write("&dob=" + URLEncoder.encode(req.getParameter("dob"), "UTF-8"));
            writer.write("&name=" + URLEncoder.encode(req.getParameter("name"), "UTF-8"));
            writer.write("&address=" + URLEncoder.encode(req.getParameter("address"), "UTF-8"));
            writer.write("&gender=" + URLEncoder.encode(req.getParameter("gender"), "UTF-8"));
            writer.write("&race=" + URLEncoder.encode(req.getParameter("race"), "UTF-8"));
            writer.write("&serviceName=" + URLEncoder.encode(req.getParameter("serviceName"), "UTF-8"));

            // Those two are non-standard attributes used for routing
            writer.write("&referrer=" + URLEncoder.encode(req.getParameter("referrer"), "UTF-8"));
            if ("1".equals(req.getParameter("sendToPatient"))) {
                writer.write("&sendToPatient=" + URLEncoder.encode("1", "UTF-8"));
            } else {
                writer.write("&sendToPatient=" + URLEncoder.encode("0", "UTF-8"));
            }

            writer.write("&type=" + URLEncoder.encode(req.getParameter("type"), "UTF-8"));
            writer.write("&title=" + URLEncoder.encode("Lab results from ACME Labs", "UTF-8"));
            writer.write("&description=" + URLEncoder.encode(req.getParameter("note"), "UTF-8"));

            if (req.getParameter("testResult1") != null && !"".equals(req.getParameter("testResult1"))) {
                writer.write("&testresults=" + URLEncoder.encode(req.getParameter("testName1") + "|" + req.getParameter("testResult1") + "|" + req.getParameter("testResultUnit1") + "|" + req.getParameter("testResultNormalRange1"), "UTF-8"));
            }
            if (req.getParameter("testResult2") != null && !"".equals(req.getParameter("testResult2"))) {
                writer.write("&testresults=" + URLEncoder.encode(req.getParameter("testName2") + "|" + req.getParameter("testResult2") + "|" + req.getParameter("testResultUnit2") + "|" + req.getParameter("testResultNormalRange2"), "UTF-8"));
            }
            if (req.getParameter("testResult3") != null && !"".equals(req.getParameter("testResult3"))) {
                writer.write("&testresults=" + URLEncoder.encode(req.getParameter("testName3") + "|" + req.getParameter("testResult3") + "|" + req.getParameter("testResultUnit3") + "|" + req.getParameter("testResultNormalRange3"), "UTF-8"));
            }
            if (req.getParameter("testResult4") != null && !"".equals(req.getParameter("testResult4"))) {
                writer.write("&testresults=" + URLEncoder.encode(req.getParameter("testName4") + "|" + req.getParameter("testResult4") + "|" + req.getParameter("testResultUnit4") + "|" + req.getParameter("testResultNormalRange4"), "UTF-8"));
            }
            if (req.getParameter("testResult5") != null && !"".equals(req.getParameter("testResult5"))) {
                writer.write("&testresults=" + URLEncoder.encode(req.getParameter("testName5") + "|" + req.getParameter("testResult5") + "|" + req.getParameter("testResultUnit5") + "|" + req.getParameter("testResultNormalRange5"), "UTF-8"));
            }
            if (req.getParameter("testResult6") != null && !"".equals(req.getParameter("testResult6"))) {
                writer.write("&testresults=" + URLEncoder.encode(req.getParameter("testName6") + "|" + req.getParameter("testResult6") + "|" + req.getParameter("testResultUnit6") + "|" + req.getParameter("testResultNormalRange6"), "UTF-8"));
            }

            writer.write("&doctorName=" + URLEncoder.encode(req.getParameter("doctorName"), "UTF-8"));
            // writer.write("&doctorTitle=" + URLEncoder.encode("Technician", "UTF-8"));

            writer.close();

            log.info ("Closed writer stream");

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                log.info ("HTTP REsponse code from Connector is OK");
                resp.sendRedirect("/demo_acme_labs/success.jsp");
            } else {
                log.info ("HTTP REsponse code from Connector is NOT OK");
                resp.setContentType("text/html");
                resp.getWriter().println("The exchange server returns a bad HTTP code");
            }
        } catch (MalformedURLException e) {
            log.log (Level.SEVERE, e.getMessage(), e);
            resp.setContentType("text/html");
            resp.getWriter().println("Malformed URL");
        } catch (IOException e) {
            // This is most likely caused by the GAE 5 sec timeout for URL fetch
            log.log (Level.SEVERE, e.getMessage(), e);
            resp.sendRedirect("/demo_acme_labs/success.jsp");
        }

    }
}
